15. 使用actionCreators和constants优化代码

使用actionCreators和constants优化代码

创建src/pages/home/store/actionCreators,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import axios from 'axios'
import * as constants from './constants'

const changeHomeData = (result) =>({
type: constants.CHANGE_HOME_DATA,
topicList: result.topicList,
articleList: result.articleList,
recommendList: result.recommendList
})

export const getHomeInfo = () =>{
return (dispatch) => {
axios.get('/api/home.json').then((res) => {
const result = res.data.data
const action = changeHomeData(result)
dispatch(action);
})
}
}

src/pages/home/index.js中使用actionCreators
componentDidMount 生命周期函数

1
2
3
componentDidMount(){
this.props.changeHomeData()
}

1
2
3
4
5
6
const mapDispatch = (dispatch) => ({
changeHomeData(){
const action = actionCreators.getHomeInfo()
dispatch(action)
}
})

constante.js中的内容

1
export const CHANGE_HOME_DATA = 'home/CHANGE_HOME_DATA'

代码地址